package com.shan.mybatis.aop;

import com.alibaba.fastjson.JSONObject;
import com.shan.mybatis.mapper.OperateLogMapper;
import com.shan.mybatis.pojo.OperateLog;
import com.shan.mybatis.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Author: ShanYuqing
 * @Version: v1.0
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper logMapper;

    @Around("@annotation(com.shan.mybatis.anno.Log)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取登录产生的Token，从中获取id
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = (Integer) claims.get("id");
        //操作时间
        LocalDateTime now = LocalDateTime.now();
        //操作类名
        String name = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String method = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] arg = joinPoint.getArgs();
        String args = Arrays.toString(arg);
         long start = System.currentTimeMillis();
        //方法返回值
        Object proceed = joinPoint.proceed();
        String jsonString = JSONObject.toJSONString(proceed);

        long end = System.currentTimeMillis();
        Long costTime = end - start;
        OperateLog log = new OperateLog(null,id,now,name,method,args,jsonString,costTime);
        logMapper.insert(log);

        return proceed;

    }
}
